<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>YAML to JSON Converter</title>
  <!-- 引入Element UI的CSS -->
  <link rel="stylesheet" href="https://thanhugo.oss-cn-shenzhen.aliyuncs.com/static/index.css">
  <style>
    /* 自定义样式 */
    body {
      font-family: Arial, sans-serif;
      background-color: #f5f7fa;
      margin: 0;
      padding: 20px;
    }
    #app {
      max-width: 1200px;
      margin: 0 auto;
    }
    .el-row {
      margin-bottom: 20px;
    }
    .el-col {
      padding: 10px;
    }
    .el-textarea {
      font-family: monospace; /* 使用等宽字体，方便对齐 */
    }
    .el-button {
      margin-top: 10px;
    }
    .json-container {
      position: relative;
    }
    .copy-button {
      position: absolute;
      right: 10px;
      top: 10px;
      z-index: 1;
    }
    .error-message {
      color: #f56c6c;
      margin-top: 10px;
      font-size: 14px;
    }
    .button-group {
      display: flex;
      gap: 10px;
    }
    .button-group .el-button {
      flex: 1;
    }
    .json-actions {
      margin-top: 10px;
      display: flex;
      gap: 10px;
    }
  </style>
</head>
<body>
<div id="app">
  <!-- Tab标签 -->
  <el-tabs v-model="activeTab" type="card">
    <!-- 第一个Tab：YAML转JSON -->
    <el-tab-pane label="YAML转JSON" name="yaml-to-json">
      <!-- 页面布局 -->
      <el-row :gutter="20">
        <!-- 左侧YAML输入 -->
        <el-col :span="12">
          <el-card shadow="hover">
            <template #header>
              <span>YAML 输入</span>
            </template>
            <el-input
                    type="textarea"
                    :rows="20"
                    placeholder="请输入YAML格式内容"
                    v-model="yamlText"
                    class="yaml-input">
            </el-input>
            <!-- 按钮组 -->
            <div class="button-group">
              <el-button type="primary" @click="parseYaml">解析</el-button>
              <el-button type="danger" @click="clearYaml">清空</el-button>
            </div>
            <!-- 错误信息显示 -->
            <div v-if="errorMessage" class="error-message">
              {{ errorMessage }}
            </div>
          </el-card>
        </el-col>
        <!-- 右侧JSON输出 -->
        <el-col :span="12">
          <el-card shadow="hover" class="json-container">
            <template #header>
              <span>JSON 输出</span>
            </template>
            <el-input
                    type="textarea"
                    :rows="20"
                    placeholder="生成的JSON内容"
                    v-model="jsonText"
                    readonly
                    class="json-output">
            </el-input>
            <!-- JSON操作按钮组 -->
            <div class="json-actions">
              <el-button type="info" @click="formatJson">格式化</el-button>
              <el-button type="warning" @click="compressJson">压缩</el-button>
              <el-button type="success" @click="copyJson">复制JSON</el-button>
              <el-button type="success" @click="clearResult('json')">清空结果</el-button>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </el-tab-pane>

    <!-- 第二个Tab：YAML转目录 -->
    <el-tab-pane label="YAML转目录" name="yaml-to-directory">
      <!-- 页面布局 -->
      <el-row :gutter="20">
        <!-- 左侧YAML输入 -->
        <el-col :span="12">
          <el-card shadow="hover">
            <template #header>
              <span>YAML 输入</span>
            </template>
            <el-input
                    type="textarea"
                    :rows="20"
                    placeholder="请输入YAML格式内容"
                    v-model="yamlText"
                    class="yaml-input">
            </el-input>
            <!-- 按钮组 -->
            <div class="button-group">
              <el-button type="primary" @click="parseYamlToDirectory">解析</el-button>
              <el-button type="danger" @click="clearYaml">清空</el-button>
            </div>
            <!-- 错误信息显示 -->
            <div v-if="errorMessage" class="error-message">
              {{ errorMessage }}
            </div>
          </el-card>
        </el-col>
        <!-- 右侧目录路径输出 -->
        <el-col :span="12">
          <el-card shadow="hover" class="json-container">
            <template #header>
              <span>目录路径输出</span>
            </template>
            <el-input
                    type="textarea"
                    :rows="20"
                    placeholder="生成的目录路径"
                    v-model="directoryText"
                    readonly
                    class="json-output">
            </el-input>
            <!-- 操作按钮组 -->
            <div class="json-actions">
              <el-button type="success" @click="copyDirectory">复制目录路径</el-button>
              <el-button type="success" @click="clearResult('dir')">清空结果</el-button>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </el-tab-pane>
  </el-tabs>
</div>

<!-- 引入Vue和Element UI的JS -->
<!-- import Vue before Element -->
<script src="https://thanhugo.oss-cn-shenzhen.aliyuncs.com/static/vue.min.js"></script>
<!-- import JavaScript -->
<script src="https://thanhugo.oss-cn-shenzhen.aliyuncs.com/static/index.js"></script>
<!-- 引入js-yaml库用于解析YAML -->
<script src="https://thanhugo.oss-cn-shenzhen.aliyuncs.com/static/js-yaml.min.js"></script>
<script>
  new Vue({
    el: '#app',
    data() {
      return {
        activeTab: 'yaml-to-json', // 当前激活的Tab
        yamlText: '', // YAML输入内容
        jsonText: '', // JSON输出内容
        directoryText: '', // 目录路径输出内容
        errorMessage: '' // 错误信息
      };
    },
    methods: {
      parseYaml() {
        try {
          // 使用 js-yaml 的 loadAll 方法解析 YAML
          const documents = jsyaml.loadAll(this.yamlText);
          if (documents.length === 0) {
            throw new Error('YAML内容为空');
          }
          // 将解析结果转换为 JSON 字符串
          this.jsonText = JSON.stringify(documents, null, 2);
          this.errorMessage = ''; // 清空错误信息
        } catch (e) {
          // 捕获解析错误
          this.errorMessage = `YAML解析失败：${e.message}`;
          this.jsonText = ''; // 清空JSON输出
        }
      },
      parseYamlToDirectory() {
        try {
          // 使用 js-yaml 的 loadAll 方法解析 YAML
          const documents = jsyaml.loadAll(this.yamlText);
          if (documents.length === 0) {
            throw new Error('YAML内容为空');
          }
          // 将YAML解析为目录路径
          const paths = this.generateDirectoryPaths(documents[0]);
          this.directoryText = `(\n  "${paths.join('",\n  "')}"\n)`;
          this.errorMessage = ''; // 清空错误信息
        } catch (e) {
          // 捕获解析错误
          this.errorMessage = `YAML解析失败：${e.message}`;
          this.directoryText = ''; // 清空目录路径输出
        }
      },
      generateDirectoryPaths(obj, prefix = '') {
        let paths = [];
        for (const key in obj) {
          if (Array.isArray(obj[key])) {
            // 如果是数组，遍历数组中的每一项
            obj[key].forEach(item => {
              if (typeof item === 'string') {
                // 如果是字符串，直接拼接路径
                paths.push(`${prefix}${key}/${item}`);
              } else if (typeof item === 'object') {
                // 如果是对象，递归处理
                paths = paths.concat(this.generateDirectoryPaths(item, `${prefix}${key}/`));
              }
            });
          } else if (typeof obj[key] === 'object') {
            // 如果是对象，递归处理
            paths = paths.concat(this.generateDirectoryPaths(obj[key], `${prefix}${key}/`));
          } else {
            // 其他情况（如字符串），直接拼接路径
            paths.push(`${prefix}${key}/${obj[key]}`);
          }
        }
        return paths;
      },
      clearYaml() {
        // 清空YAML输入框和错误信息
        this.yamlText = '';
        this.errorMessage = '';
        this.jsonText = '';
        this.directoryText = '';
      },
      copyJson() {
        if (!this.jsonText) {
          this.$message.warning('没有可复制的内容');
          return;
        }
        navigator.clipboard.writeText(this.jsonText).then(() => {
          this.$message.success('JSON内容已复制到剪贴板');
        }).catch(() => {
          this.$message.error('复制失败');
        });
      },
      copyDirectory() {
        if (!this.directoryText) {
          this.$message.warning('没有可复制的内容');
          return;
        }
        navigator.clipboard.writeText(this.directoryText).then(() => {
          this.$message.success('目录路径已复制到剪贴板');
        }).catch(() => {
          this.$message.error('复制失败');
        });
      },
      formatJson() {
        if (!this.jsonText) {
          this.$message.warning('没有可格式化的内容');
          return;
        }
        try {
          // 将JSON字符串解析为对象，再格式化为带缩进的字符串
          const jsonObj = JSON.parse(this.jsonText);
          this.jsonText = JSON.stringify(jsonObj, null, 2);
          this.$message.success('JSON格式化成功');
        } catch (e) {
          this.$message.error('JSON格式化失败：内容不是有效的JSON');
        }
      },
      compressJson() {
        if (!this.jsonText) {
          this.$message.warning('没有可压缩的内容');
          return;
        }
        try {
          // 将JSON字符串解析为对象，再压缩为单行字符串
          const jsonObj = JSON.parse(this.jsonText);
          this.jsonText = JSON.stringify(jsonObj);
          this.$message.success('JSON压缩成功');
        } catch (e) {
          this.$message.error('JSON压缩失败：内容不是有效的JSON');
        }
      },
      clearResult(value) {
        switch (value) {
          case 'json':
            this.jsonText = '';
            break;
          case 'dir':
            this.directoryText = '';
            break;
          default:
            break;
        }
      }
    }
  });
</script>
</body>
</html>